package com.android.basewars;

import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

public class RegisterActivity extends Activity {
	EditText editUsername, editEmail, editPassword, editPasswordAgain;
	Button buttonRegister;
	
	private final int REGISTER_SUCCES = 0; 
	 @Override
	    public void onCreate(Bundle savedInstanceState) {
	        super.onCreate(savedInstanceState);
	        setContentView(R.layout.registerview);
	        
	        setupViews();
	        setListeners();
	    }

	private void register(){
		//REGISTER!
		
		// Create a new HttpClient and Post Header
		
		if(validate()){
		    HttpClient httpclient = new DefaultHttpClient();
		    HttpPost httppost = new HttpPost("http://frankkie.nl/basewars/api/v4/register");
	
		    try {
		        // Add your data
		        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
		        nameValuePairs.add(new BasicNameValuePair("username", editUsername.getText().toString()));
		        nameValuePairs.add(new BasicNameValuePair("email", editEmail.getText().toString()));
		        nameValuePairs.add(new BasicNameValuePair("password", convertMD5(editPassword.getText().toString())));
		        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
	
		        // Execute HTTP Post Request
		        HttpResponse response = httpclient.execute(httppost);
		        
		        showDialog(REGISTER_SUCCES);
		    } catch (ClientProtocolException e) {
		        // TODO Auto-generated catch block
		    } catch (IOException e) {
		        // TODO Auto-generated catch block
		    }
		}
		
	}
	
	public String convertMD5(String s){
        try {
            // Create MD5 Hash
            MessageDigest digest = java.security.MessageDigest.getInstance("SHA1");
            digest.update(s.getBytes());
            byte messageDigest[] = digest.digest();
            
            // Create Hex String
            StringBuffer hexString = new StringBuffer();
            for (int i=0; i<messageDigest.length; i++)
                hexString.append(Integer.toHexString(0xFF & messageDigest[i]));
            return hexString.toString();
            
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return "";
	}
	
	@Override
    protected Dialog onCreateDialog(int id) {
        switch (id) {
		case REGISTER_SUCCES:
			 return new AlertDialog.Builder(RegisterActivity.this)
              .setTitle("Succes!")
              .setMessage("U bent succesvol geregistreed!")
              .setPositiveButton("Oke", new DialogInterface.OnClickListener() {
                  public void onClick(DialogInterface dialog, int whichButton) {
                	  //naar log in scherm!
                	  	Intent login = new Intent(getApplicationContext(), LogInActivity.class);
               			startActivity(login);
               			finish();
                  }
              })
			 .create();
    	}
        return null;
    }
	
	
	private boolean validate(){
		boolean isValidate = true;
		
		//E-mailadres
    	Pattern emailadres = Pattern.compile(".+@.+\\.[a-zA-z-0-9]+");
    	Matcher emailadresInvoer = emailadres.matcher(editEmail.getText().toString());
    	boolean emailadresvelden = emailadresInvoer.matches(); 
    	if (emailadresvelden == false)
    	{
    		editEmail.setError("Ongeldig e-mailadres");
    		isValidate = false;
    	}
    	//Gebruikersnaam
    	Pattern gebruikersnaam = Pattern.compile("");
    	Matcher gebruikersnaamInvoer = gebruikersnaam.matcher(editUsername.getText().toString());
    	boolean gebruikersnaamVeld = gebruikersnaamInvoer.matches(); 
    	if (gebruikersnaamVeld == true)
    	{
    		editUsername.setError("Username is verplicht!");
    		isValidate = false;
    	}
    	
    	//Wachtwoorden
    	String eerste_wachtwoord = editPassword.getText().toString();
    	String tweede_wachtwoord = editPasswordAgain.getText().toString();
    	
    	Pattern wachtwoord = Pattern.compile("");
    	Matcher wachtwoordInvoer = wachtwoord.matcher(editPassword.getText().toString());
    	boolean wachtwoordVeld = wachtwoordInvoer.matches();  
    	if (wachtwoordVeld == true)
    	{
    		editPassword.setError("Wachtwoord is verplicht!");
    		isValidate = false;
    	}
    	
    	Pattern herhaalWachtwoord = Pattern.compile("");
    	Matcher herhaalWachtwoordInvoer = herhaalWachtwoord.matcher(editPasswordAgain.getText().toString());
    	boolean herhaalWachtwoordVeld = herhaalWachtwoordInvoer.matches();  
    	if (herhaalWachtwoordVeld == true)
    	{
    		editPasswordAgain.setError("Wachtwoord controle verplicht!");
    		isValidate = false;
    	}
    	
    	boolean controleer = eerste_wachtwoord.equals(tweede_wachtwoord) && tweede_wachtwoord.equals(eerste_wachtwoord);
    	if(controleer == false)
		{
	    	editPassword.setError("Wachtwoorden komen niet overeen!");
	        editPasswordAgain.setError("Wachtwoorden komen niet overeen!");
	        isValidate = false;
		}
		
		return isValidate;
	}
	
	private void setListeners() {
		buttonRegister.setOnClickListener
    	( new View.OnClickListener(){@Override public void onClick(View v) {register();}});
	}

	private void setupViews() {
		editUsername = 		(EditText)findViewById(R.id.editTextUsernameReg);
		editEmail = 		(EditText)findViewById(R.id.editTextEmailReg);
		editPassword = 		(EditText)findViewById(R.id.editTextPasswordReg);
		editPasswordAgain =	(EditText)findViewById(R.id.editTextPasswordAgainReg);
		
		buttonRegister =	(Button)findViewById(R.id.buttonRegisterForBaseWars);
	}
}
